package com.dongdongqiang.daogenerator.handler.impl;

import com.dongdongqiang.daogenerator.exception.DDQException;
import com.dongdongqiang.daogenerator.handler.IDeleteHandler;
import com.dongdongqiang.daogenerator.pojo.TableMeta;
import com.dongdongqiang.daogenerator.sqlbuilder.DeleteSQLBuilder;
import com.dongdongqiang.daogenerator.utils.POJOUtils;
import com.dongdongqiang.daogenerator.tablemetabuilder.TableMetaBuilderImpl;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * PostgreSQL 删除方法
 * Created by ZZB on 2017/9/25.
 */
public class DeleteHandlerImpl implements IDeleteHandler {
    private DeleteSQLBuilder deleteSQLBuilder;

    public DeleteHandlerImpl(DeleteSQLBuilder deleteSQLBuilder) {
        this.deleteSQLBuilder = deleteSQLBuilder;
    }

    public <T> int deleteByPk(Object pk, Class<T> tClass, Connection connection) throws DDQException {
        TableMeta tableMeta = TableMetaBuilderImpl.obtainByClass(tClass);
        String sql = deleteSQLBuilder.buildDeleteSQL(tableMeta);
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setObject(1,pk);
            return preparedStatement.executeUpdate();
        } catch (SQLException e) {
            throw new DDQException(e);
        }
    }

    public <T> int[] deleteInPk(List<Object> pk, Class<T> tClass, Connection connection) throws DDQException {
        TableMeta tableMeta = TableMetaBuilderImpl.obtainByClass(tClass);
        String sql = deleteSQLBuilder.buildDeleteSQL(tableMeta);
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            for (Object o : pk) {
                preparedStatement.setObject(1,o);
                preparedStatement.addBatch();
            }
            return preparedStatement.executeBatch();
        } catch (SQLException e) {
            throw new DDQException(e);
        }
    }

    public int delete(Object o, Connection connection) throws DDQException {
        TableMeta tableMeta = TableMetaBuilderImpl.obtainByObject(o);
        String sql = deleteSQLBuilder.buildDeleteSQL(tableMeta);
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            Object pk = POJOUtils.readDeclaredFieldByGetMethod(o,tableMeta.getPrimaryKeyColumn().getPropertyName());
            preparedStatement.setObject(1,pk);
            return preparedStatement.executeUpdate();
        } catch (SQLException | NoSuchFieldException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new DDQException(e);
        }
    }
}
